import {menuTreeAllApi} from "@/api/sys/MenuApi";
import {useMenuListStore} from "@/stores/counter";
import {dynamicMenuRoutes} from "@/router/constructRouter";
import router from "@/router/index";
import {routes} from "@/router/permission";
import type {MenuTypes} from "@/resources/interface/sys/MenuTypes";

export const constructMenuRouter = async (menuTree: MenuTypes[]) => {
    if (menuTree.length === 0) {
        let treeAllApi = await menuTreeAllApi();
        menuTree = treeAllApi.data
    }
    for (let menuType of menuTree) {
        if (!routes[0].children.some(item => item.component === menuType.component)) {
            routes[0].children.push(menuType)
        }
    }
    const menuListStore = useMenuListStore();
    let menuRoutes = dynamicMenuRoutes(routes);
    menuListStore.saveMenuList(menuTree)
    for (let menuRoute of menuRoutes) {
        router.addRoute(menuRoute);
    }
}
